package com.bankLogisticsSys.service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

import com.bankLogisticsSys.model.Expresscontent;
import com.bankLogisticsSys.model.Expressinfo;
import com.bankLogisticsSys.model.Expresspath;
import com.bankLogisticsSys.model.Expressprocess;
import com.bankLogisticsSys.model.Expressrecord;
import com.bankLogisticsSys.model.Packageinfo;
import com.bankLogisticsSys.model.Userinfo;
import com.bankLogisticsSys.util.TrackingID;

public class LogisticsService {
	
	//操作 get揽收， send 发送 receive 接受 pack 封包 accept 验收
	public static final int GET_ACTION = 0;
	public static final int SEND_ACTION = 1;
	public static final int RECEIVE_ACTION = 2;
	public static final int PACK_ACTION = 3;
	public static final int ACCEPT_ACTION = 4;
	
	//快递单的状态 验收/运输/拒收
	public static final int ACCEPT = 0;
	public static final int TRANSPORT = 1;
	public static final int REJECT = 2;
	
	public static final int POSTMAN = 5;

	ExpressService exservice = new ExpressService();
	PackageService pkservice = new PackageService();
	
	//添加新的快递单
	public long createExpress(Userinfo user){
		Boolean flag;
		if(user.getRole()%2 == 1)
		{
			flag = true;
		}else{
			flag = false;
		}
		Expressinfo ei = new Expressinfo();
		Date currentDate = new Date(System.currentTimeMillis());
		TrackingID ti = new TrackingID(user.getId()%31, 0);
		Long trackingID = ti.nextId();
		ei.setSource(user.getNetworkID());
		ei.setTrackingID(trackingID);
		ei.setSendDate(currentDate);
		ei.setState(1);
		ei.setFlag(flag);
		ei.setBank(user.getBank());
		ei.save();
		return trackingID;
	}
	//空包退回，添加新的快递单
	public long createExpress2(Userinfo user,int orderNum,int networkid,int businessID){
		Boolean flag;
		if(user.getRole()%2 == 1)
		{
			flag = true;
		}else{
			flag = false;
		}
		Expressinfo ei = new Expressinfo();
		Date currentDate = new Date(System.currentTimeMillis());
		TrackingID ti = new TrackingID(user.getId()%31, orderNum%31);
		Long trackingID = ti.nextId();
		ei.setSource(user.getNetworkID());
		ei.setDestination(networkid);
		ei.setTrackingID(trackingID);
		ei.setSendDate(currentDate);
		ei.setBusinessID(businessID);
		ei.setState(1);
		ei.setFlag(flag);
		ei.setBank(user.getBank());
		ei.save();
		return trackingID;
	}
	
	
	//更新快递单
	public void updateOrder(Userinfo user, int trackingID, int state){
		Expressinfo ei = Expressinfo.dao.findFirst("select * from expressinfo where trackingid = ?", trackingID);
		java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
		
		if(state == 4){
			ei.setReceiveDate(currentDate);
			ei.setState(4);
		}else{
			ei.setState(state);
		}
		ei.update();
	}
	//添加包裹到快递单
	public void addPackage(long trackingID, int packageID){
		Packageinfo pi = pkservice.getPackage(packageID);
		pi.setState(2);
		pi.update();
		//小包
		if(pi.getType()==0){
			Expresscontent ec = new Expresscontent();
			ec.setTrackingID(trackingID);
			ec.setPackageID(packageID);
			ec.setRemarks("123456");
			ec.save();
		}else{
			//大包
			List<Expresscontent> ecList = exservice.getContentList(trackingID);
			Expresscontent ec = new Expresscontent();
			for(int i=0, size=ecList.size();i<size;i++){
				ec = ecList.get(i);
				if(ec.getBpackageID()== null){
					ec.setBpackageID(packageID);
				}
				ec.update();
			}
			Expresscontent ecB = new Expresscontent();
			ecB.setTrackingID(trackingID);
			ecB.setPackageID(packageID);
			ecB.save();
		}
	}
	
	//获取下一站的位置
	public int getNextNetwork(Expressinfo ei,int sequence){
		int next;
		System.out.println("sequence!!!!!!!!!!!!!!!\n" + sequence);
		next = TransformService.getSequenceNetwork(sequence+1, ei.getSource(),ei.getBusinessID(),ei.getFlag());
		//上下行路线变了，都是递增的下一站位置
//		if(ei.getFlag()){
//			next = TransformService.getSequenceNetwork(sequence+1, ei.getSource());
//		}else{
//			next = TransformService.getSequenceNetwork(sequence-1, ei.getDestination());
//		}
		return next;
	}
	
	public String processMsg(long trackingID, String openId, int action, int sequence){
		String msg;
		String msgFinish="";
		Userinfo user = exservice.getUserinfo(openId);
		Expressinfo ei = exservice.getInfoByTrackingID(trackingID);
		
		if(user.getNetworkID().equals(ei.getSource())){
			action = PACK_ACTION;
			msg = "\n揽投站： " + TransformService.getNetwork(getNextNetwork(ei, sequence)) + "将派员工前来揽收";
		}else if(user.getNetworkID().equals(ei.getDestination())){
			action = ACCEPT_ACTION;
			if(user.getRole()==2){
			msg = "\n<a href=\"http://fiberkenzo.com/weixin/accept/returnPk/" + ei.getTrackingID() + "\">空包退回</a>";
			}else{
				msg="";
			}
		}else if(action == SEND_ACTION){
			msg = "\n快递即将发往： " + TransformService.getNetwork(getNextNetwork(ei, sequence));
		}else if(action == GET_ACTION){
			String next;
			if(ei.getFlag()){
				next = TransformService.getNetwork(TransformService.getSequenceNetwork(sequence, ei.getSource(),ei.getBusinessID(),ei.getFlag()));
			}else{
				next = TransformService.getNetwork(TransformService.getSequenceNetwork(sequence, ei.getDestination(),ei.getBusinessID(),ei.getFlag()));
			}
			msg = "\n快递即将发往:" + next;
		}else{
			msg = "";
		}
		msgFinish = "您对快递单： " + ei.getTrackingID() + "的" + TransformService.getAction(action) + "操作已经完成!";
		msgFinish += msg;
		
		return msgFinish;
	}
	
	//用于后台显示的流程信息
	public String processMsg2(long trackingID, String employeeID, int action, int sequence){
		String msg;
		String msgFinish="";
		Userinfo user = exservice.getUserinfoByID(employeeID);
		Expressinfo ei = exservice.getInfoByTrackingID(trackingID);
		System.out.println("user.getNetworkID: " + user.getNetworkID() + "ei.getSource:" + ei.getSource());
		if(user.getNetworkID().equals(ei.getSource())){
			action = PACK_ACTION;
			msg = "\n  " + TransformService.getNetwork(getNextNetwork(ei, sequence)) + "将派员工前来揽收";
		}else if(user.getNetworkID().equals(ei.getDestination())){
			action = ACCEPT_ACTION;
			msg = "";
		}else if(action == SEND_ACTION){
			msg = "\n  快递即将发往： " + TransformService.getNetwork(getNextNetwork(ei, sequence));
		}else if(action == GET_ACTION){
//			String next;
//			if(ei.getFlag()){
//				next = TransformService.getNetwork(TransformService.getSequenceNetwork(sequence, ei.getSource()));
//			}else{
//				next = TransformService.getNetwork(TransformService.getSequenceNetwork(sequence, ei.getDestination()));
//			}
//			msg = "\n  快递即将发往:" + next;
			msg = "\n  快递即将发往： " + TransformService.getNetwork(getNextNetwork(ei, sequence));
		}else{
			msg = "";
		}
		msgFinish = TransformService.getNetwork(user.getNetworkID()) +"  员工 " + user.getName() + "： 已" + TransformService.getAction(action);
		msgFinish += msg;
		
		return msgFinish;
	}
	
	//流程处理
	public Boolean dealProcess(long trackingID, int sequence, int abnormal,int action ,String openId){
		Userinfo user = exservice.getUserinfo(openId);
		System.out.println(user.getEmployeeID());
		Expressprocess ep = exservice.getProcessUser(trackingID, user.getEmployeeID(), action);
		System.out.println(ep);
		Expressinfo ei = exservice.getInfoByTrackingID(trackingID);

		if(ep == null){
			LogisticsService ls = new LogisticsService();
			if(ls.addProcess(trackingID, sequence,abnormal, action, user)){
				if(abnormal != 0){
					ei.setAbnormal(abnormal);
					ei.update();
				}
				return updateState(action, ei);
			}
			return false;
		}else{
			return false;	
		}
	}
	
	public Boolean updateState(int action , Expressinfo ei){
		if(action != 4){
			ei.setState(TRANSPORT);
		}else{
			java.sql.Date receiveDate = new java.sql.Date(System.currentTimeMillis());
			ei.setState(ACCEPT);
			ei.setReceiveDate(receiveDate);
		}
		return ei.update();
	}
	//添加操作流程
	public Boolean addProcess(long trackingID, int sequence,int abnormal,int action, Userinfo user){
		java.sql.Timestamp t = new Timestamp(System.currentTimeMillis());
		Expressprocess ep = new Expressprocess();
		ep.setAction(action);
		ep.setSequence(sequence);
		ep.setEmployeeID(user.getEmployeeID());
		ep.setNetworkID(user.getNetworkID());
		ep.setTrackingID(trackingID);
		ep.setTime(t);
		ep.setConfirm(abnormal);
		ep.setRemarks("test");
		return ep.save();
	}
	
	//添加操作流水
	public void addRecord(long trackingID, int packageID, int action, Userinfo user){
		java.sql.Timestamp t = new Timestamp(System.currentTimeMillis());
		Expressrecord er = new Expressrecord();
		
		er.setEmployeeID(user.getEmployeeID());
		er.setPackageID(packageID);
		er.setTrackingID(trackingID);
		er.setAction(action);
		er.setNetworkID(user.getNetworkID());
		er.setTime(t);
		er.save();
		
		Packageinfo pi = Packageinfo.dao.findFirst("select * from packageinfo where id= ?", packageID);
		pi.setLocation(user.getNetworkID());
		pi.update();
	}
	
	//判断包裹是否属于当前快递单
	public Boolean isBelong(long trackingID, int packageID, Userinfo user){
		Expresscontent ec = exservice.getContentByPack(trackingID, packageID);
		Expressinfo ei = exservice.getInfoByTrackingID(trackingID);
		if(ec == null && !user.getNetworkID().equals(ei.getSource())){
			return false;
		}
		return true;
	}
	
	//判断是否重复扫码
	public Boolean isRepeatScan(long trackingID, Userinfo user, int packageid, int action){
		Expressrecord er = exservice.getRecord(trackingID, user.getEmployeeID(), packageid, action);
		System.out.println(er);
		return (er!=null);
	}
	
	//判断快递单号对应的数据是否存在
	public Boolean isExistExpress(long trackingID){
		Expressinfo ei = exservice.getInfoByTrackingID(trackingID);
		return (ei!=null);
	}
	
	//判断是否完善包裹信息，目的地
	public boolean setDestination(long trackingID, Packageinfo pi){
		Expressinfo ei = Expressinfo.dao.findFirst("select * from expressinfo where trackingID = ?", trackingID);
		Expresspath ep = Expresspath.dao.findFirst("select * from expresspath p "
				+ "where p.networkID = ? and p.businessID= ? and p.flag = ? order by sequence desc",
				pi.getNetworkID(),pi.getBusinessID(), ei.getFlag());
		if(ep==null)return false;
		System.out.println("/////////////////////////destination and bussiness" + ep.getPathID()+ pi.getBusinessID());
		if(ei.getDestination()==null){
			ei.setDestination(ep.getPathID());
			ei.setBusinessID(pi.getBusinessID());
//			if(flag){
//				ei.setDestination(TransformService.getDestination(pi.getNetworkID()));
//			}else{
//				ei.setDestination(pi.getNetworkID());
//			}
			ei.update();
		}
		return true;
	}
	
	public Boolean getTrackingIDByRecord(Expressrecord er){
		if(er!=null){
			long temp = er.getTrackingID();
			Expressinfo ei = exservice.getNotFinishInfo(temp);
			return (ei!=null);
		}else{
			return false;
		}
	}
	
	public Boolean isPathError(Expressinfo ei,Userinfo user, int sequence, Boolean flag){
		if(user.getRole()!= POSTMAN){
			int temp;
			if(flag){
				temp = ei.getSource();
			}else{
				temp = ei.getDestination();
			}
			if(user.getNetworkID() != TransformService.getSequenceNetwork(sequence, temp, ei.getBusinessID(),ei.getFlag())){ 
				return true;
			}else return false;
		}else{
			return false;
		}
	}
	public Boolean isExistPath(Expressinfo ei){
		int temp;
		if(ei.getFlag()){
			temp = ei.getSource();
		}else{
			temp = ei.getDestination();
		}
		Expresspath path = Expresspath.dao.findFirst("select * from expresspath where networkid = ?", temp);
		return (path!=null);
	}
}
